import { createDictionary, deleteDictionary, getDictionaries, updateDictionary } from "@/api/dictionary";
import { formatFormItem, FormItemType, FormTableItemType } from "@/components/FormByData/FormByData";
import Table, { TableRef } from "@/components/Table";
import { Card, Space, Button, message, FormInstance } from "antd";
import { MutableRefObject, useRef, useState } from "react";
import { useNavigate } from "react-router";
import { Operation } from "@/typings/common";
import { StatusOptions } from "@/constant/common";
import { formatDate } from "@/utils/date";
import TableSwitch from "@/components/TableSwitch";
import { DatabaseOutlined, EditOutlined } from "@ant-design/icons";
import FormByData from "@/components/FormByData/FormByData";
import { CreateDictionaryReq, Dictionary as DictionaryType, UpdateDictionaryReq } from "@/typings/api";
import Search from "@/components/Search";
import Modal from "@/components/Modal/Modal";

type SearchFields = Pick<DictionaryType, "title" | "key">;

const Dictionary = () => {
    const navigate = useNavigate();
    const columns: FormTableItemType<UpdateDictionaryReq>[] = [
        { dataIndex: "title", title: "标题", required: true },
        { dataIndex: "key", title: "字典值", required: true },
        {
            dataIndex: "status",
            title: "状态",
            type: "radio",
            options: StatusOptions,
            render: (_, record) => (
                <TableSwitch<UpdateDictionaryReq>
                    dataIndex="status"
                    getList={tableRef.current!.getList}
                    updateRecord={updateDictionary}
                    record={record}
                />
            ),
        },
        { dataIndex: "remark", title: "备注", type: "textarea" },
        { dataIndex: "updatedAt", title: "更新时间", render: val => formatDate(val), isForm: false },
        { dataIndex: "operation", title: "操作", isForm: false },
    ];

    const [modalShow, setModalShow] = useState(false);
    const [opType, setOpType] = useState<Operation>("add");
    const currentRecord = useRef<UpdateDictionaryReq>();

    const handleAdd = () => {
        setOpType("add");
        setModalShow(true);
        formRef.current?.resetFields();
    };

    const clickEdit = (record: UpdateDictionaryReq) => {
        setOpType("edit");
        setModalShow(true);
        formRef.current?.resetFields();
        formRef.current?.setFieldsValue(record);
        currentRecord.current = record;
    };

    const tableRef = useRef<TableRef>(null);
    const formRef: MutableRefObject<FormInstance<UpdateDictionaryReq> | null> = useRef(null);
    const submit = async () => {
        const formData = await formRef.current?.validateFields?.();
        if (!formData) return;
        if (opType === "add") {
            await createDictionary(formData as CreateDictionaryReq);
            message.success("创建成功");
        } else {
            if (!currentRecord.current) return;
            await updateDictionary({ ...formData, _id: currentRecord.current._id });
            message.success("编辑成功");
        }
        tableRef.current?.getList();
        setModalShow(false);
    };

    const searchFormItems: FormItemType[] = [
        { label: "标题", name: "title" },
        { label: "字典值", name: "key" },
    ];
    const searchParams = useRef<Partial<DictionaryType>>({});
    const handleSearch = async (formData: SearchFields) => {
        searchParams.current = formData;
        await tableRef.current?.getList(1, 10);
    };

    const searchFromRef = useRef<FormInstance>();
    const handleReset = () => {
        searchFromRef.current?.resetFields();
        searchParams.current = {};
        tableRef.current?.getList(1, 10);
    };
    return (
        <Card
            title={
                <Search<SearchFields>
                    title="字典管理"
                    formItems={searchFormItems}
                    onReset={handleReset}
                    onAdd={handleAdd}
                    onSearch={handleSearch}
                    getFormRef={ref => (searchFromRef.current = ref)}
                />
            }
        >
            <Table<UpdateDictionaryReq>
                ref={tableRef}
                columns={columns}
                getApi={p => getDictionaries({ ...p, ...searchParams.current })}
                delApi={deleteDictionary}
                actionMore={record => (
                    <Space>
                        <Button type="primary" size="small" icon={<EditOutlined />} onClick={() => clickEdit(record)}>
                            编辑
                        </Button>
                        <Button size="small" icon={<DatabaseOutlined />} onClick={() => navigate(`/system/dictionaryItems?_id=${record._id}`)}>
                            数据
                        </Button>
                    </Space>
                )}
            />

            <Modal
                title={`${opType === "add" ? "添加" : "编辑"}字典`}
                open={modalShow}
                onCancel={() => setModalShow(false)}
                onOk={submit}
                forceRender
            >
                <FormByData
                    getFormRef={ref => (formRef.current = ref)}
                    formItems={formatFormItem(columns)}
                    cols={1}
                    formProps={{ initialValues: { status: true } }}
                />
            </Modal>
        </Card>
    );
};

export default Dictionary;
